<template>
  <div class="login-container">
    <!-- 渐变背景 -->
    <div class="gradient-background"></div>
    
    <!-- 登录卡片 -->
    <div class="login-card">
      <!-- 头部区域 -->
      <div class="login-header">
        <img 
          alt="Meiden Logo" 
          class="company-logo"
          src="../assets/svg/meiden_logo.svg"
        />
        <h1 class="login-title">系统登录</h1>
      </div>
      
      <!-- 表单区域 -->
      <div class="login-form">
        <div class="form-group">
          <n-input
            v-model:value="loginInfo.username"
            autofocus
            class="form-input"
            placeholder="请输入用户名"
            :maxlength="20"
          />
        </div>
        
        <div class="form-group">
          <n-input
            v-model:value="loginInfo.password"
            class="form-input"
            type="password"
            show-password-on="mousedown"
            placeholder="请输入密码"
            :maxlength="20"
          />
        </div>
        
        <div class="form-actions">
          <n-button
            class="login-button"
            type="primary"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </n-button>
        </div>
        
        <!-- 移除测试按钮，保留登录功能 -->
      </div>
    </div>
    
    <!-- 页脚 -->
    <footer class="login-footer">
      <p>明电舍(杭州)电气系统有限公司 &copy; {{ new Date().getFullYear() }}</p>
    </footer>
  </div>
</template>

<script setup>
import { NInput, NButton, useMessage, NConfigProvider } from "naive-ui";
import { useRouter } from "vue-router";
import { ref } from "vue";
import axios from "axios";
import { API_URLS } from '../utils/apiConfig';

const router = useRouter();
const message = useMessage();
const loginInfo = ref({
  username: "",
  password: "",
});

// 移除图标相关代码，简化表单实现

// 存储token到cookie的方法
const setCookie = (name, value, days = 7) => {
  const date = new Date();
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  const expires = `expires=${date.toUTCString()}`;
  document.cookie = `${name}=${encodeURIComponent(value)}; ${expires}; path=/`;
};

// 从cookie获取token的方法
const getCookie = (name) => {
  const nameEQ = `${name}=`;
  const cookies = document.cookie.split(";");
  for (let i = 0; i < cookies.length; i++) {
    let cookie = cookies[i];
    while (cookie.charAt(0) === " ") cookie = cookie.substring(1);
    if (cookie.indexOf(nameEQ) === 0) {
      return decodeURIComponent(cookie.substring(nameEQ.length));
    }
  }
  return null;
};

const loading = ref(false);

// 登录逻辑
const handleLogin = async () => {
  if (!loginInfo.value.username || !loginInfo.value.password) {
    message.warning("未输入用户名或密码");
    return;
  }
  try {
    loading.value = true;
    console.log("登录中.....");

    const response = await axios.post(
      API_URLS.user.accessToken,
      loginInfo.value
    );

    // 后端返回的token字段为access_token
    const token = response.data.data.access_token;
    if (token) {
      // 存储token到cookie，有效期7天
      setCookie("access_token", token, 1);

      // 存储用户名到localStorage
      localStorage.setItem('username', loginInfo.value.username);
      console.log("登录成功，token已存储到cookie，用户名已存储到localStorage");
      
      // 登录成功后跳转到实时位置页面
      router.push("/AGV/AGV_position");
    }
  } catch (error) {
    // 错误处理逻辑：获取并打印状态码和详细信息
    if (error.response) {
      const statusCode = error.response.status;
      const errorData = error.response.data;
      const detail = errorData.detail || "未知错误信息";
      message.error(`登录失败: ${detail} (状态码: ${statusCode})`);
    } else if (error.request) {
      message.error("登录失败：无法连接到服务器，请检查网络");
    } else {
      message.error("登录失败 - 其他错误:" + error.message);
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 全局样式重置 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* 登录容器 */
.login-container {
  min-height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  padding: 20px;
}

/* 渐变背景 */
.gradient-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  z-index: -1;
}

/* 登录卡片 */
.login-card {
  background: white;
  border-radius: 20px;
  padding: 40px;
  width: 100%;
  max-width: 450px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.login-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 45px rgba(0, 0, 0, 0.15);
}

/* 登录头部 */
.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.company-logo {
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
  transition: transform 0.3s ease;
}

.company-logo:hover {
  transform: scale(1.05);
}

.login-title {
  font-size: 28px;
  color: #333;
  font-weight: 600;
  margin: 0;
}

/* 登录表单 */
.login-form {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
  height: 50px;
  border-radius: 12px;
  font-size: 16px;
  transition: border-color 0.3s ease;
}

.form-input:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

/* 表单操作按钮 */
.form-actions {
  margin-top: 30px;
}

.login-button {
  width: 100%;
  height: 50px;
  font-size: 18px;
  font-weight: 600;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
}

.login-button:active {
  transform: translateY(0);
}

.login-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 页脚样式 */
.login-footer {
  margin-top: 40px;
  color: white;
  text-align: center;
  font-size: 14px;
  opacity: 0.8;
}

.login-footer p {
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-card {
    padding: 30px 25px;
  }
  
  .login-title {
    font-size: 24px;
  }
  
  .company-logo {
    width: 100px;
    height: 100px;
  }
  
  .form-input, .login-button {
    height: 45px;
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: 15px;
  }
  
  .login-card {
    padding: 25px 20px;
  }
  
  .login-title {
    font-size: 22px;
  }
  
  .company-logo {
    width: 90px;
    height: 90px;
  }
}
</style>
